<template>
  <view class="animated fadeIn faster">
    <view class="page-bg">
      <view :style="{'height': titleBarHeight + 'px','paddingTop':statusBarHeight+'px'}"
            class="d-flex d-flex-center d-flex-middle">
        <text :style="{'height': menuButtonHeight-8 + 'px'}" class="font32">答题系统</text>
      </view>
      <view class="d-flex d-flex-between px-2 d-flex-middle pt-2">
        <view class="searchBox px-2 rounded20 d-flex-item d-flex d-flex-middle">
          <input v-model="formData.name" class="pl-1 rounded10 font30 d-flex-item" placeholder="课程名称"
                 placeholder-class="colorhold"/>
          <text v-if="formData.name" class="text-right iconfont icon-cuo1  ml-2"
                @click="dataCancel"></text>
          <text class="iconfont icon-icon_sousuo main-color font40  text" @click="onSearch"></text>
        </view>
        <view class="ml-2 headimg d-flex d-flex-center d-flex-middle" @click="goMy">
          <image v-if="loginState" :src="avatar" mode="aspectFill"></image>
          <text v-else class="main-color">登录</text>
        </view>
      </view>
    </view>

    <view class="mx-2 py-2">
      <swiper :duration="1000" :interval="5000" autoplay class="position-relative rounded10"
              indicator-active-color="#ffffff"
              indicator-color="#c6c8c5" indicator-dots
              style="width:100%;height: 260rpx;overflow: hidden;">
        <block v-for="(item,idx) in banner" :key="idx+'a'">
          <swiper-item>
            <view class="swiper-item">
              <image :src="item.image" class="rounded10" lazy-load
                     mode="aspectFill"
                     style="width:100%;height: 240rpx;" @click="goUrl(item.url)">
              </image>
            </view>
          </swiper-item>
        </block>
      </swiper>
    </view>

    <view class="d-flex d-flex-between mx-2 d-flex-middle">
      <NoticeBar :notices="notices" class="d-flex-item font28"/>
      <view class="see-more-btn pl-1 font24 color-5C5C5CCC"
            @click="goUrl('/subPages/newsHome/newsHome')">
      查看详情
      </view>
    </view>

    <!-- 分类导航模块 -->
    <view class="bg-white pt-4 pb-4 d-flex flex-justify">
      <view v-for="(item, index) in categoryList" :key="index" class=" text-center d-flex d-flex-middle d-flex-column"
            @click="goUrl((item.url))">
        <image :src="item.icon" class="type-icon mb-1" mode="aspectFit"></image>
        <text class="type-txt font22 color-929292">{{ item.title }}</text>
      </view>

    </view>

    <!-- 在页面模板中添加今日推荐模块 -->
    <view class="column-model bg-white px-2 py-2 pt-0">
      <view class="column-box d-flex d-flex-between d-flex-middle pb-2">
        <text class="font30 main-color font-bold">今日推荐</text>
        <view class="see-more-btn font24 color-5C5C5CCC"
              @click="goUrl('/subPages/todayRecommendation/todayRecommendation')">
          查看详情
        </view>
      </view>
      <view class="d-flex recommend-grid1">
        <view
            v-for="(item, index) in todayRecommende"
            :key="index"
            class="recommend-data-box d-flex d-flex-column mr-2 bg-fff rounded10"
            @click="goUrl(`/subPages/courseDetails/courseDetails?id=${item.id}`)"
        >
          <image
              :src="item.course_image"
              class="recommend-picture2"
              mode="aspectFill"
          ></image>
          <view class="px-1 pt-1 pb-2">
            <view class="text-clamp font26 color-5C5C5CFF">{{ item.course_name }}</view>
            <view class="d-flex d-flex-between d-flex-middle mt-1">
              <text class="font24" style="color: rgba(55, 189, 180, 1)">免费</text>
              <text class="font20 color-5C5C5CCC">
                <text>{{ item.sort }}</text>
                同学正学习
              </text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <view class="px-2">
      <view class="d-flex tab-scroll_box">
        <view v-for="(item,index) in listType" :key="index+'1'"
              :class="{'grabClassActive':tabsIndex == item.id}" class="tab-scroll_item font30 main-color pr-3 py-1 "
              @click="getType(item.id,index)">
          {{ item.name }}
        </view>
      </view>
      <view :class="tabsIndex == 1?'recommend-grid1':'recommend-grid'">
        <view
            v-for="(item, index) in recommendList"
            :key="index"
            class="recommend-data-box bg-fff rounded10 d-flex d-flex-column"
            @click="goUrl(`/subPages/courseDetails/courseDetails?id=${item.id}`)"
        >
          <image
              :class="tabsIndex == 1?'recommend-picture2':'recommend-picture'"
              :src="item.course_image"
              mode="aspectFill"
          ></image>
          <view class="px-1 pt-1 pb-2">
            <view class="colorf00" style="color: rgba(55, 189, 180, 1)">免费</view>
            <view class="text-clamp font26 color-5C5C5CFF mt-1">{{ item.course_name }}</view>
            <view class="d-flex d-flex-between d-flex-middle mt-1">
              <text class="font20 color-5C5C5CCC">
                <text>{{ item.sort }}</text>
                位同学正在学习
              </text>
            </view>
          </view>
        </view>
      </view>
    </view>


  </view>
</template>

<script>
import {
  mapState
} from "vuex"
// import {homeApi} from '@/http/homeApi.js';
import NoticeBar from '@/components/notice-bar/index.vue'
import {homeApi} from "@/http/homeApi";

export default {
  components: {
    NoticeBar
  },
  data() {
    return {
      formData: {
        name: ''
      },
      banner: [
        {
          image: 'https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/exam/718-20230505194915-20230828151536.jpg',
          url: ''
        }
      ],
      notices: [],
      categoryList: [{
        icon: 'https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/exam/type1.png',
        title: '会员中心',
        url: '/subPages/memberCenter/memberCenter'
      },
        {
          icon: 'https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/exam/type3.png',
          title: '积分商城',
          url: '/subPages/pointsMall/pointsMall'
        },
        // {
        //   icon: 'https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/exam/type2.png',
        //   title: '电子资料',
        //   url: '/subPages/electron/electron'
        // }
      ],
      currentPage: 0,
      todayRecommende: [],
      listType: [
        {
          name: '热门课程',
          id: 0
        },
        {
          name: '讲师推荐',
          id: 1
        },
        {
          name: '最新好课',
          id: 2
        },
      ],
      tabsIndex: 0,
      recommendList: [],
    }
  },
  computed: {
    ...mapState({
      statusBarHeight: state => state.statusBarHeight,
      menuButtonHeight: state => state.menuButtonHeight,
      titleBarHeight: state => state.titleBarHeight,
      avatar: state => state.avatar,
      loginState: state => state.loginState
    }),
    // 将分类列表分页，每页4个
    categoryPages() {
      const pages = [];
      const itemsPerPage = 5;
      for (let i = 0; i < this.categoryList.length; i += itemsPerPage) {
        pages.push(this.categoryList.slice(i, i + itemsPerPage));
      }
      return pages;
    }
  },
  onLoad() {
    this.goTodayRecommende()
    this.goHotCourse()
    this.goBanner()
    this.goNotificationsLatest()
  },
  methods: {
    async goBanner() {
      let res = await homeApi.getBanner()
      this.banner = res
    },
    async goTodayRecommende() {
      let res = await homeApi.getTodayRecommended()
      this.todayRecommende = res.slice(0, 3)
    },
    async goNotificationsLatest() {
      let res = await homeApi.getNotificationsLatest()
      console.log(res)
      this.notices = res
    },
    getType(id, index) {
      // 更新当前选中的tab索引
      this.tabsIndex = id;
      switch (id) {
        case 0:
          this.goHotCourse()
          break;
        case 1:
          this.goTeacherRecommended()
          break;
        case 2:
          this.goLatestCourses()
          break;
      }
    },
    async goHotCourse() {
      let res = await homeApi.getHotCourse()
      this.recommendList = res
    },
    async goTeacherRecommended() {
      let res = await homeApi.getTeacherRecommended()
      this.recommendList = res
    },
    async goLatestCourses() {
      let res = await homeApi.getLatestCourses()
      this.recommendList = res
    },
    // 清除搜索
    dataCancel() {
      this.formData.name = ''
    },
    // 跳转到个人中心
    goMy() {
      if (this.loginState) {
        uni.navigateTo({
          url: '/pages/mine/mine'
        })
      } else {
        uni.navigateTo({
          url: '/subPages/login/login'
        })
      }
    },
    // 跳转到分类页面
    goCategory(item) {
      if (item.url) {
        uni.navigateTo({
          url: item.url
        })
      }
    },
    // 获取数据
    onSwiperChange(e) {
      this.currentPage = e.detail.current;
    },
    goUrl(urlPages, data) {
      if (!this.loginState) {
        uni.showToast({
          title: '未登录，请先登录！',
          icon: 'none'
        })
        setTimeout(() => {
          uni.navigateTo({
            url: '/subPages/login/login'
          })
        }, 1500)
      } else {
        uni.navigateTo({
          url: urlPages
        })
      }
    },
    // 搜索功能
    onSearch() {
      if (this.formData.name.trim()) {
        // 跳转到搜索页面并传递搜索关键词
        uni.navigateTo({
          url: `/subPages/homeSearch/homeSearch?keyword=${encodeURIComponent(this.formData.name)}`
        });
      } else {
        uni.showToast({
          title: '请输入搜索内容',
          icon: 'none'
        });
      }
    },
    // 清除搜索
    dataCancel() {
      this.formData.name = '';
    }
  }
}
</script>

<style scoped>
.page-bg {
  background: linear-gradient(180deg, rgba(62, 142, 254, 0.8) 0%, rgba(62, 142, 254, 0) 100%);
}

.color-929292 {
  color: rgba(92, 92, 92, 1);
}

.viewMain {
  margin-bottom: 90rpx;
}

.flex-justify {
  justify-content: space-evenly
}

.searchBox {
  background-color: #fff;
  height: 80rpx;
  line-height: 80rpx;
}

.searchBox input {
  height: 100%;
}

.headimg {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  overflow: hidden;
}

.headimg image {
  width: 100%;
  height: 100%;
}


.type-swiper {
  height: 120rpx;
  width: 100%;
}

.type-icon {
  width: 160rpx;
  height: 140rpx;
}

/* 自定义指示器样式 - 横线形式 */
.custom-indicator {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 10rpx 0;
}

.indicator-line {
  width: 30rpx;
  height: 6rpx;
  background-color: #c6c8c5;
  border-radius: 0;
  margin: 0 5rpx;
  transition: all 0.3s ease;
}

.indicator-line.active {
  background-color: #007AFF;
  width: 50rpx;
}

/* 今日推荐模块样式 */


.recommend-txt {
  color: #333;
  line-height: 1.4;
}

.recommend-scroll {
  width: 100%;
  white-space: nowrap;
  padding-bottom: 10rpx;
}

.recommend-data-box {
  width: 220rpx;
  display: inline-flex;
}

.grabClassActive {
  font-weight: bold;
  text-decoration: underline;
}


.course-category {
  background-color: #e8f4ff;
}

.course-category .grab {
  border-right: 2rpx solid #cedeef;
}

.course-category .grab:last-child {
  border-right: 0 solid #f4f6fa;
}

.color-5C5C5CCC {
  color: #5C5C5CCC;
}


.tab-scroll_box {
  display: flex;
  align-items: center;
  flex-wrap: nowrap;
  box-sizing: border-box;
  overflow-x: auto; /* 允许横向滚动 */
  -webkit-overflow-scrolling: touch; /* iOS滚动优化 */
}

.tab-scroll_item {
  line-height: 60rpx;
  flex-shrink: 0;
  display: flex;
  justify-content: center;
  white-space: nowrap; /* 防止文字换行 */
}

.recommend-grid1 {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20rpx;
}

.recommend-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
}

.recommend-data-box {
  width: 100%;
}

.recommend-picture2 {
  width: 100%;
  height: 220rpx;
  border-radius: 10rpx;
}

.recommend-picture {
  width: 100%;
  height: 348rpx;
  border-radius: 10rpx;
}
</style>
